package com.yue92.datalife.controller.v1;

import com.yue92.datalife.common.CommonUtil;
import com.yue92.datalife.helper.AnalysisHelper;
import com.yue92.datalife.helper.RecordHelper;
import com.yue92.datalife.model.Record;
import com.yue92.datalife.model.User;
import com.yue92.datalife.response.AnalysisLineSingleRes;
import com.yue92.datalife.response.ResponseResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

import static com.yue92.datalife.common.Constant.CURRENT_USER_ATTRIBUTE;

@RestController
@RequestMapping(value = "/api/v1/analysis", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class AnalysisController {

    @Autowired
    private AnalysisHelper analysisHelper;

    @Autowired
    private RecordHelper recordHelper;

    @GetMapping("/line-single")
    public ResponseResource<AnalysisLineSingleRes> index(@RequestParam("record_id") Long recordId, @RequestParam(value = "record_date", required = false) String recordDate, @RequestParam(value = "year_offset", required = false) Integer yearOffset, @RequestParam(value = "cumulate", required = false) Boolean cumulate, @RequestAttribute(CURRENT_USER_ATTRIBUTE) User currentUser) {

        Record record = recordHelper.checkAndGetRecord(recordId, currentUser);
        LocalDate date = CommonUtil.getLocalDate(recordDate, yearOffset, ChronoUnit.YEARS);

        if (cumulate == null) {
            cumulate = true;
        }

        return ResponseResource.success(analysisHelper.index(record, date, cumulate));
    }
}
